#include "version2device.h"
#include "File/Xml/BasicXml.h"
Version2Device::Version2Device(QObject *parent) :
    BaseInterface<Version2Device>(parent)
{
    m_pInstance = this;
    version2Protocol = new Version2Protocol(this);
    m_rebootTimerCount=0;
    BasicXml *basicXml = BasicXml::getInstance();
        qDebug()<<"intervalReboot - "<<basicXml->rebootIntervalTIme();
        qDebug()<<"RebootTimePoint - "<<basicXml->rebootTimePoint();

        if(basicXml->rebootIntervalTIme() > 0)
        {
            notifyRebootTimer = new QTimer(this);
            connect(notifyRebootTimer, SIGNAL(timeout()), this, SLOT(NotifyRebootSlot()));
            notifyRebootTimer->setInterval(1000);
            notifyRebootTimer ->start();
            m_isFirstNotify=1;
        }

    this->registerProtocol(version2Protocol);
    this->setIsDecrypt(true);
    this->setIsEncrypt(true);
    registerCmdHandler(SynchrosystemCmd::FunctionCode,SynchrosystemCmd::staticMetaObject, &Version2Device::SynchroSystemCmdHandle);
}

void Version2Device::SynchroSystemCmdHandle(PortStruct source,QSharedPointer<BaseCmd> sharedCmd)
{
     Q_UNUSED(sharedCmd);
    qDebug()<<"synchroSystem now";
    Package package;
    SavePointXml *savePointXml =SavePointXml::getInstance();
    QByteArray pointDeviceData;
    QByteArray body;
    quint16 bodylength=0;
    QMap<quint16,SavePointStruct>dataMap=savePointXml->getMap();
    QList<quint16>dataList=savePointXml->getList();

    foreach(const quint16 &addr,dataList)
    {
        bodylength++;
        SavePointStruct getStruct=dataMap.value(addr);
        pointDeviceData.append(DataTypeConver::intToByteArray(getStruct.pointAddr(),2));
        pointDeviceData.append(DataTypeConver::intToByteArray(getStruct.pointValue(),2));
    }
    bodylength=pointDeviceData.size();
    body.append(DataTypeConver::intToByteArray(bodylength,2));
    body.append(pointDeviceData);
    package.setBody(body);
    package.setFunction(0x09);
    package.setId(0x01);
    pointDeviceData=version2Protocol->generateData(package);
    emit sendDataSignal(source,pointDeviceData);

    /**************************/
    static QMutex mutex;
    mutex.lock();
    QString text;
    QString currentTime = QDateTime::currentDateTime().toString("[yyyy-MM-dd hh:mm:ss]");
    text = currentTime + "panel reboot now" + "\r\n";
    QByteArray textArray = text.toLatin1();
    fprintf(stderr, textArray.constData());

    QFile file(QCoreApplication::applicationDirPath() + "/panelreboot.txt");
    file.open(QIODevice::WriteOnly | QIODevice::Append);
    QTextStream textStream(&file);
    textStream << text;
    file.flush();
    if(file.size()>0x100000)
    {
        file.remove();
    }
    file.close();

    mutex.unlock();

    /**************************/

}

void Version2Device::NotifyRebootSlot()
{

    //Package package;
   // QByteArray pointDeviceData;
    bool ok;
    QString curdate = QDate::currentDate().toString("yyyy-MM-dd");
    QString year = curdate.mid(0,4);
    QString month = curdate.mid(5,2);
    QString date = curdate.mid(8,2);
    QString curtime = QTime::currentTime().toString("hh:mm:ss");
    QString hour = curtime.mid(0,2);
    QString min = curtime.mid(3,2);
    QString sec = curtime.mid(6,2);
    PortStruct target;
    if(sec == "00")
    {
     qDebug()<<curdate<<" year:"<<year<<"month:"<<month<<"date:"<<date;
     qDebug()<<curtime<<" hour:"<<hour<<"min:"<<min<<"sec:"<<sec;

    }

    m_rebootTimerCount++;

    if(year.toInt(&ok,10)>=2022)
    {
         BasicXml *basicXml = BasicXml::getInstance();
    // if(m_isFirstNotify == 1)
         if(sec == "00")
         qDebug()<<"m_rebootTimerCount "<<QString::number(m_rebootTimerCount,10)<<"--"<<QString::number(basicXml->rebootIntervalTIme()*1440*60,10)<<"--m_isFirstNotify-"<<QString::number(m_isFirstNotify,10);
     if((((hour.toInt()==basicXml->rebootTimePoint())&&(min=="00")) && ((sec=="00")||(sec=="03")))&&((m_rebootTimerCount >= basicXml->rebootIntervalTIme()*1440*60)||(m_isFirstNotify==1)))
     {

        m_isFirstNotify=0;
        m_rebootTimerCount=0;

    foreach (const BasePort *port , m_portList)
    {
         if((port->portParam().type() == "UART" && port->portParam().name() == "RS485"))
         {
             target = port->portParam();
         }
    }



    Package package;

    QByteArray pointDeviceData;
    QByteArray body;
    quint16 bodylength=0;



    bodylength=8;
    body.append(DataTypeConver::intToByteArray(0,2));
    body.append(DataTypeConver::intToByteArray(0,2));
    body.append(DataTypeConver::intToByteArray(0xffff,2));
    body.append(DataTypeConver::intToByteArray(0xffff,2));
    package.setBody(body);
    package.setFunction(NotifyRebootCmd::FunctionCode);
    package.setId(0x01);
    pointDeviceData=version2Protocol->generateData(package);
     emit sendDataSignal(target,pointDeviceData);
     }
}

}
